package com.github.tvbox.osc.util;


import android.app.Activity;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.view.Window;
import android.widget.Toast;

import com.github.tvbox.osc.R;
import com.github.tvbox.osc.base.App;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.orhanobut.hawk.Hawk;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class WallpaperUtil {
    static final ExecutorService executorService = Executors.newFixedThreadPool(4);

    public static String getCache() {
        final String cacheJsonConfig = Hawk.get(Hawk.get(HawkConfig.API_CACHE_KEY, ""), null);
        JsonObject infoJson = new Gson().fromJson(cacheJsonConfig, JsonObject.class);
        return DefaultConfig.safeJsonString(infoJson, "wallpaper", null);
    }

    public static void setAppBackgroundImage(Activity activity) {
        executorService.execute(() -> {
            try {
                String wallpaperUrl = getCache();
                if (wallpaperUrl == null || wallpaperUrl.length() == 0) {
                    activity.runOnUiThread(() -> Toast.makeText(App.getInstance(), "没有读取到壁纸源", Toast.LENGTH_SHORT).show());
                    return;
                }
                Window window = activity.getWindow();
                byte[] data = getWallpaperFromUri(wallpaperUrl);
                Hawk.delete(HawkConfig.APP_BACKGROUND_IMAGE);
                String base64 = Base64.getEncoder().encodeToString(data);
                Hawk.put(HawkConfig.APP_BACKGROUND_IMAGE, base64);
                Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
                Drawable drawable = DrawableUtil.bitmapToDrawable(activity.getApplicationContext(), bm);
                activity.runOnUiThread(() -> window.setBackgroundDrawable(drawable));
            } catch (Exception e) {
                LOG.e("切换壁纸失败" + e);
            }
        });
    }

    public static void setAppBackgroundImageFromCache(Activity activity) {
        executorService.execute(() -> {
            try {
                Window window = activity.getWindow();
                String base64 = Hawk.get(HawkConfig.APP_BACKGROUND_IMAGE, null);
                if (base64 != null) {
                    byte[] data = Base64.getDecoder().decode(base64);
                    Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
                    Drawable drawable = DrawableUtil.bitmapToDrawable(activity.getApplicationContext(), bm);
                    activity.runOnUiThread(() -> window.setBackgroundDrawable(drawable));
                } else {
                    resetAppBackgroundImage(activity);
                }
            } catch (Exception e) {
                LOG.e("切换壁纸失败" + e);
            }
        });
    }

    public static byte[] getWallpaperFromUri(String uri) throws IOException {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .get()
                .url(uri)
                .build();
        Call call = client.newCall(request);
        //同步调用,返回Response,会抛出IO异常
        Response response = call.execute();
        return response.body().bytes();
    }

    public static void resetAppBackgroundImage(Activity activity) {
        try {
            Hawk.delete(HawkConfig.APP_BACKGROUND_IMAGE);
            Window window = activity.getWindow();
            Resources resources = activity.getApplicationContext().getResources();
            Drawable drawable = resources.getDrawable(R.drawable.app_bg);
            activity.runOnUiThread(() -> window.setBackgroundDrawable(drawable));
        } catch (Exception e) {
            LOG.e("切换壁纸失败" + e);
        }
    }
}
